package com.demo.controller;

import java.io.File;

import com.demo.common.model.User;
import com.demo.constants.Constants;
import com.demo.constants.GeneralUtil;
import com.demo.service.UserService;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

public class UserController extends Controller {

    static UserService service = new UserService();

    public void index() {
        render("index.html");
    }

    public void audit() {
        Page<User> page = service.paginate(1, 10);
        setAttr("page", page);
        render("audit.html");
    }

    public void doaudit() {
        Integer userId = getParaToInt(0);
        Integer status = getParaToInt(1);
        service.doaudit(userId, status);
        renderJson();
    }

    public void userinfo() {
        User suser = getSessionAttr(Constants.SESSION_LOGIN_USER);
        User user = User.dao.findById(suser.getId());
        setAttr("user", user);
        render("userinfo.html");
    }

    public void saveuserinfo() {

        UploadFile photo = getFile("photo");
        User user = getBean(User.class, "", true);
        if (photo != null) {
            String fileName = photo.getFileName();
            fileName = GeneralUtil.getUUID() + fileName.substring(fileName.lastIndexOf("."));
            File file = photo.getFile();
            file.renameTo(new File(file.getParentFile(), fileName));
            user.setPhoto(fileName);
        }

        User suser = getSessionAttr(Constants.SESSION_LOGIN_USER);
        user.setId(suser.getId());
        user.update();
        setSessionAttr(Constants.SESSION_LOGIN_USER, User.dao.findById(suser.getId()));
        redirect("/user/userinfo");
    }

    public void search() {
        Page<User> paginate = service.paginate(1, 10);
        render("audit.html");
    }

    public void logout() {
        getSession().invalidate();
        redirect("/login");
    }

}
